<template>
  <el-dialog
    title="添加部门"
    :visible="dialogVisible"
    @close="closeDialog"
    @open="openDialog"
  >
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form ref="deptForm" label-width="120px" :model="form" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <div slot="footer">
      <el-button type="primary" size="small" @click="submit">确定</el-button>
      <el-button size="small" @click="closeDialog">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { reqGetEmployeeSimple } from '@/api/employees'
import { reqAddDepartments } from '@/api/departments'
export default {
  name: 'AddDept',
  props: {
    // 弹层展示
    dialogVisible: {
      type: Boolean,
      default: false
    },
    // 节点数据
    nodeData: {
      type: Object,
      required: true
    },
    // 完整的列表数据（非树桩）
    depts: {
      type: Array,
      required: true
    }
  },
  data() {
    const validateName = (rule, value, callback) => {
      // 简单版本
      // const isRepeat = this.depts.some(item => item.name === value)
      // isRepeat ? callback(new Error(`已有${value}部门名称`)) : callback()
      // -------------------------------------
      // 复杂版本
      const children = this.depts.filter(item => item.pid === this.nodeData.id)
      // 开发完成后，肯定要校验同级部门不能有重复 不同级部门可以有重复
      const isRepeat = children.some(item => item.name === value)
      isRepeat ? callback(new Error(`同级部门已有${value}部门名称`)) : callback()
    }

    const validateCode = (rule, value, callback) => {
      const isRepeat = this.depts.some(item => item.code === value)
      isRepeat ? callback(new Error(`已有${value}部门编码`)) : callback()
    }
    return {
      options: [],
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入部门信息', trigger: ['change', 'blur'] },
          { min: 1, max: 50, message: '请输入1-50个字符', trigger: ['change', 'blur'] },
          { validator: validateName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: ['change', 'blur'] },
          { min: 1, max: 50, message: '请输入1-50个字符', trigger: ['change', 'blur'] },
          { validator: validateCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请输入部门信息', trigger: ['change', 'blur'] }
          // { min: 1, max: 50, message: '请输入1-50个字符', trigger: ['change', 'blur'] }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: ['change', 'blur'] },
          { min: 1, max: 300, message: '请输入1-300个字符', trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  async created() {
    this.getEmployeeSimple()
  },
  methods: {
    async submit() {
      // 回调函数的写法
      // this.$refs.deptForm.validate((flag) => {
      //   if (flag) {
      //     console.log('校验通过')
      //   } else {
      //     console.log('校验失败')
      //   }
      // })

      // this.$refs.deptForm.validate().then(() => {
      //   console.log('校验通过')
      // }).catch(() => {
      //   console.log('校验失败')
      // })
      try {
        await this.$refs.deptForm.validate()
        console.log('校验通过')
        // 1、掉接口
        // 2、提示
        // 3、刷新列表
        // 4、关闭弹层
        await reqAddDepartments({ ...this.form, pid: this.nodeData.id })
        this.$message.success('添加成功')
        this.$emit('add-depts')
        this.closeDialog()
      } catch (error) {
        console.log('校验失败')
      }
    },
    // 打开弹层的回调
    openDialog() {
      // console.log('open')
      // this.getEmployeeSimple()
    },
    // 获取员工的简单列表
    async getEmployeeSimple() {
      const { data } = await reqGetEmployeeSimple()
      // console.log(data)
      this.options = data
    },
    closeDialog() {
      this.$emit('update:dialogVisible', false)
      this.$refs.deptForm.resetFields()
    }
  }

}
</script>

<style>

</style>
